package com.eystar.pdc.model;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.eystar.ext.plugin.tablebind.ModelExt;
import com.eystar.ext.plugin.tablebind.TableBind;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.SqlPara;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;

/**
 * 角色资源的Model
 * @author auth
 *
 */
@TableBind(tableName = "t_pdc_role_resource")
public class RoleResource extends ModelExt<RoleResource> {

	private static final long serialVersionUID = 1244431359124317083L;
	public final static RoleResource dao = new RoleResource();
	
	/**
	 * 根据角色id和资源id，查询某个角色拥有资源的关键字有哪些
	 * @param roleId
	 * @param resourceId
	 * @return
	 */
	public JSONArray findResourceAuthSigns(String roleId,String resourceId){
		JSONArray array = new JSONArray();

		Resource resources = Resource.dao.findById(resourceId);
		String authSignsString = resources.getStr("auth_signs"); // 某个资源对应的关键字
		if (StrUtil.isNotBlank(authSignsString)) { // 如果这个资源有关键字
			Kv kv = Kv.by("sign_names", StrUtil.split(authSignsString, ","));
			SqlPara sqlPara = getSqlPara("pdc.auth_sign.findAuthSignByName", kv);
			List<AuthSign> authSigns = AuthSign.dao.find(sqlPara); // 某个资源对应的关键字
			// 查询这个资源，这个角色有哪些权限关键字，为了方便选中
			Map<String, Object> columns = new HashMap<String, Object>();
			columns.put("resource_id", resourceId);
			columns.put("role_id", roleId);
			RoleResource roleResources = RoleResource.dao.findFirstByColumnsSecurity(columns);
			for (AuthSign authSign : authSigns) {
				JSONObject object = new JSONObject();
				object.put("id", authSign.getStr("id"));
				object.put("sign_name", authSign.getStr("sign_name"));
				object.put("sign_remark", authSign.getStr("sign_remark"));
				if (roleResources != null && StrUtil.indexOfIgnoreCase(roleResources.getStr("auth_signs"), authSign.getStr("sign_name")) != -1) {
					object.put("checked", 1);
				} else {
					object.put("checked", 0);
				}
				array.add(object);
			}
		}
		return array;
	}
	
	/**
	 * 添加角色资源信息
	 * @param signs
	 * @param roleId
	 */
	public void addRoleResouces(String[] signs,String roleId,String resourceId){
		// 1、先删除之前的角色权限分配关系
		Db.update(getSql("pdc.role_resource.deleteRoleResource"), roleId,resourceId);
		// 2、添加新的角色和权限关系
		if (signs == null || signs.length == 0) {
			return;
		}
		RoleResource roleResources = new RoleResource();
		roleResources.set("role_id", roleId);
		roleResources.set("resource_id", resourceId);
		roleResources.set("auth_signs", ArrayUtil.join(signs,","));
		roleResources.save();
	}
}